import React, { useState, useEffect } from 'react'
import { View, Button, Image, Text } from '@tarojs/components'
import { AtDivider, AtActivityIndicator, AtButton, AtCard, AtMessage } from 'taro-ui'
import EChart from 'techarts'
import Taro from '@tarojs/taro'
// 自定义构建的echarts
import * as echarts from './../../echarts'
import {
  getCanvasVideo,
  getVideoHistory,
  getWordCloud
} from '../../../../api/index'
import './index.scss'

interface PersonalDetail {
  face: string
  name: string
  OfficialVerifyDesc: string
  sign: string
  fans: number
  archiveView: number //播放总数
  likes: number
  totalFavourite: number //收藏
  archiveCount: number //作品总数
  totalCount: number //充电总数
  totalDanmaku: number
  totalComment: number
}

interface DurationType {
  row: string
  value: number
}

interface VideoHistoryData {
  likes: Array<DurationType>
  fans: Array<DurationType>
  archiveView: Array<DurationType>
  archiveCount: Array<DurationType>
  articleView: Array<DurationType>
  articleCount: Array<DurationType>
  totalCount: Array<DurationType>
  danmu: Array<DurationType>
  collect: Array<DurationType>
  comments: Array<DurationType>
  likesInc: Array<DurationType>
  fansInc: Array<DurationType>
  archiveViewInc: Array<DurationType>
  archiveCountInc: Array<DurationType>
  articleViewInc: Array<DurationType>
  articleCountInc: Array<DurationType>
  totalCountInc: Array<DurationType>
  danmuInc: Array<DurationType>
  collectInc: Array<DurationType>
  commentsInc: Array<DurationType>
}

export default (props) => {
  const { id, detail } = props
  const [loading, setLoading] = useState(true)
  const [current, setCurrent] = useState(0)
  const [current_2, setCurrent_2] = useState(0)
  const [current_3, setCurrent_3] = useState(0)
  const [videoData, setVideoData] = useState<VideoHistoryData>()
  const [data, setData] = useState<PersonalDetail>(detail)
  const [option, setOption] = useState({
    title: {
      top: 0,
      left: 'center',
      text: '视频发布时间分布图'
    },
    xAxis: {
      type: 'category',
      data: [] as Array<string>
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [] as Array<number>,
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(255, 255, 255, 0.8)'
        }
      }
    ]
  })

  const [option_2, setOption_2] = useState({
    title: {
      top: 0,
      left: 'center',
      text: '视频时长分布'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} {b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 0,
      data: [
        '0分钟-1分钟',
        '1分钟-3分钟',
        '3分钟-5分钟',
        '5分钟-10分钟',
        '10分钟-20分钟',
        '20分钟-30分钟',
        '30分钟-60分钟',
        '60分钟以上'
      ]
    },
    series: [
      {
        center: ['58%', '50%'],
        name: '视频时长分布',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [] as Array<any>
      }
    ]
  })

  const [option_3, setOption_3] = useState({
    title: {
      text: '数据分析图(单位:十万)',
      top: 0,
      left: 'center'
    },
    xAxis: {
      type: 'category',
      data: [] as Array<string>
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [] as Array<number>,
        type: 'line'
      }
    ]
  })

  const [option_4, setOption_4] = useState(option)

  const setUpVideoData = (tempdata) => {
    console.log(tempdata)

    let data = tempdata?.slice()
    let xArea = [] as Array<string>
    let yArea = [] as Array<number>
    let unit = '单位: 个'

    let unitdata = data[0].value
    console.log('我是参考值', unitdata)

    let flag
    if (unitdata < 1000) {
      flag = 1
    } else if (unitdata > 1000 && unitdata < 10000) {
      flag = 2
      unit = '单位: 千'
    } else if (unitdata > 10000 && unitdata < 10000000) {
      flag = 3
      unit = '单位: 万'
    } else if (unitdata > 1000000 && unitdata < 100000000) {
      flag = 4
      unit = '单位: 千万'
    } else {
      flag = 5
      unit = '单位: 亿'
    }

    data.reverse().forEach((item) => {
      if (flag === 1) {
        xArea.push(item.row)
        yArea.push(item.value)
      } else if (flag === 2) {
        xArea.push(item.row)
        yArea.push(item.value / 1000)
      } else if (flag === 3) {
        xArea.push(item.row)
        yArea.push(item.value / 10000)
      } else if (flag === 4) {
        xArea.push(item.row)
        yArea.push(item.value / 10000000)
      } else if (flag === 5) {
        xArea.push(item.row)
        yArea.push(item.value / 100000000)
      }
    })

    setOption_3({
      title: {
        text: `数据分析图(${unit})`,
        top: 0,
        left: 'center'
      },
      xAxis: {
        type: 'category',
        data: xArea
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: yArea,
          type: 'line'
        }
      ]
    })
    setLoading(false)
  }

  useEffect(() => {
    ;(async () => {
      let xAxis = [] as Array<string>
      let yAxis = [] as Array<number>
      let durationData = [] as Array<any>

      const {
        data: {
          data: { duration, pubdate }
        }
      } = await getCanvasVideo({
        id
      })
      duration.forEach((element) => {
        let newElement = {
          name: element.row,
          value: element.value
        }
        durationData.push(newElement)
      })

      pubdate.forEach((element) => {
        xAxis.push(element.row)
        yAxis.push(element.value)
      })
      setOption({
        ...option,
        xAxis: {
          type: 'category',
          data: xAxis
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: yAxis,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(220, 220, 220, 0.8)'
            }
          }
        ]
      })

      setOption_2({
        ...option_2,
        series: [
          {
            center: ['58%', '50%'],
            name: '视频时长分布',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: durationData
          }
        ]
      })
    })()
  }, [id])

  useEffect(() => {
    ;(async () => {
      let temp = videoData || {}
      if (Object.keys(temp).length === 0) {
        const {
          data: { data, errorCode, errorMessage }
        } = await getVideoHistory({
          id,
          days: 7
        })
        if (!errorCode) {
          setUpVideoData(data.archiveCount)
          setVideoData(data)
        } else {
          Taro.atMessage({
            message: errorMessage + ',请充值',
            type: 'error'
          })
        }
      }
      if (current === 0) {
        if (current_2 === 0) {
          setUpVideoData(videoData?.archiveCount)
        } else if (current_2 === 1) {
          setUpVideoData(videoData?.archiveView)
        } else if (current_2 === 2) {
          setUpVideoData(videoData?.collect)
        } else if (current_2 === 3) {
          setUpVideoData(videoData?.comments)
        } else if (current_2 === 4) {
          setUpVideoData(videoData?.danmu)
        } else if (current_2 === 5) {
          setUpVideoData(videoData?.fans)
        }
      } else if (current === 1) {
        if (current_2 === 0) {
          setUpVideoData(videoData?.totalCountInc)
        } else if (current_2 === 1) {
          setUpVideoData(videoData?.archiveViewInc)
        } else if (current_2 === 2) {
          setUpVideoData(videoData?.collectInc)
        } else if (current_2 === 3) {
          setUpVideoData(videoData?.commentsInc)
        } else if (current_2 === 4) {
          setUpVideoData(videoData?.danmuInc)
        } else if (current_2 === 5) {
          setUpVideoData(videoData?.fansInc)
        }
      }
    })()
  }, [current, current_2])

  useEffect(() => {
    ;(async () => {
      let xAxis = [] as Array<string>
      let yAxis = [] as Array<number>
      let durationData = [] as Array<any>
      console.log(current_3)

      if (current_3 === 0) {
        let {
          data: {
            data: { title }
          }
        } = await getWordCloud({
          id
        })

        title.forEach((element) => {
          let newElement = {
            name: element.word,
            value: element.weight
          }
          durationData.push(newElement)
        })

        title.forEach((element) => {
          xAxis.push(element.word)
          yAxis.push(element.weight)
        })
        setOption_4({
          title: {
            text: '关键字分析图: 标题关键字',
            top: 0,
            left: 'center'
          },
          xAxis: {
            type: 'category',
            data: xAxis
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: yAxis,
              type: 'bar',
              showBackground: true,
              backgroundStyle: {
                color: 'rgba(220, 220, 220, 0.8)'
              }
            }
          ]
        })
      } else if (current_3 === 1) {
        let {
          data: {
            data: { description }
          }
        } = await getWordCloud({
          id
        })
        description.forEach((element) => {
          let newElement = {
            name: element.word,
            value: element.weight
          }
          durationData.push(newElement)
        })

        description.forEach((element) => {
          xAxis.push(element.word)
          yAxis.push(element.weight)
        })
        setOption_4({
          title: {
            text: '关键字分析图: 描述性关键字',
            top: 0,
            left: 'center'
          },
          xAxis: {
            type: 'category',
            data: xAxis
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: yAxis,
              type: 'bar',
              showBackground: true,
              backgroundStyle: {
                color: 'rgba(220, 220, 220, 0.8)'
              }
            }
          ]
        })
      } else if (current_3 === 2) {
        let {
          data: {
            data: { taglist }
          }
        } = await getWordCloud({
          id
        })
        taglist.forEach((element) => {
          let newElement = {
            name: element.word,
            value: element.weight
          }
          durationData.push(newElement)
        })

        taglist.forEach((element) => {
          xAxis.push(element.word)
          yAxis.push(element.weight)
        })
        setOption_4({
          title: {
            text: '关键字分析图: 标签性描述关键字',
            top: 0,
            left: 'center'
          },
          xAxis: {
            type: 'category',
            data: xAxis
          },
          yAxis: {
            type: 'value'
          },
          series: [
            {
              data: yAxis,
              type: 'bar',
              showBackground: true,
              backgroundStyle: {
                color: 'rgba(220, 220, 220, 0.8)'
              }
            }
          ]
        })
      }
    })()
  }, [current_3])
  const onInit = (canvas, width, height, dpr) => {
    const chart = echarts.init(canvas, 'light', {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    })
    return chart // 必须return
  }

  return (
    <View>
      <AtMessage></AtMessage>
      {loading ? (
        <AtActivityIndicator mode="center"></AtActivityIndicator>
      ) : (
        <View>
          <View className="page-index">
            <View className="line-chart">
              {/* 通过 option 设置数据 */}
              <EChart echarts={echarts} option={option} onInit={onInit} />
            </View>
          </View>
          <AtDivider></AtDivider>
          <View className="page-index">
            <View className="line-chart">
              {/* 通过 option 设置数据 */}
              <EChart echarts={echarts} option={option_2} onInit={onInit} />
            </View>
          </View>
          <AtDivider></AtDivider>
          <View className="page-index">
            <View style={{ margin: '0px 34rpx' }}>
              <AtButton
                type="secondary"
                size="small"
                className={current === 0 ? 'choose-btn' : 'scroll-btn'}
                onClick={() => setCurrent(0)}
              >
                总量
              </AtButton>
              <AtButton
                type="secondary"
                size="small"
                className={current === 1 ? 'choose-btn' : 'scroll-btn'}
                onClick={() => setCurrent(1)}
              >
                增量
              </AtButton>
            </View>
            <View style={{ marginLeft: '34rpx' }}>
              <AtButton
                type="secondary"
                size="small"
                className={current_2 === 0 ? 'choose-btn' : 'scroll-btn'}
                onClick={() => setCurrent_2(0)}
              >
                视频数
              </AtButton>
              <AtButton
                type="secondary"
                size="small"
                className={current_2 === 1 ? 'choose-btn' : 'scroll-btn'}
                onClick={() => setCurrent_2(1)}
              >
                观看量
              </AtButton>
              <AtButton
                type="secondary"
                size="small"
                className={current_2 === 2 ? 'choose-btn' : 'scroll-btn'}
                onClick={() => setCurrent_2(2)}
              >
                收藏数
              </AtButton>
              <AtButton
                type="secondary"
                size="small"
                className={current_2 === 3 ? 'choose-btn' : 'scroll-btn'}
                onClick={() => setCurrent_2(3)}
              >
                评论数
              </AtButton>
              <AtButton
                type="secondary"
                size="small"
                className={current_2 === 4 ? 'choose-btn' : 'scroll-btn'}
                onClick={() => setCurrent_2(4)}
              >
                弹幕数
              </AtButton>
              <AtButton
                type="secondary"
                size="small"
                className={current_2 === 5 ? 'choose-btn' : 'scroll-btn'}
                onClick={() => setCurrent_2(5)}
              >
                粉丝数
              </AtButton>
            </View>
            <View className="line-chart">
              {/* 通过 option 设置数据 */}
              <EChart echarts={echarts} option={option_3} onInit={onInit} />
            </View>
          </View>
          <AtDivider></AtDivider>
          <AtCard title="比例数据">
            <View className="card">
              <Text>
                每百次播放点赞:{' '}
                <Text className="color">
                  {((data.likes / data.archiveView) * 100).toFixed(2)}
                </Text>
              </Text>
              <Text>
                每百次播放收藏:{' '}
                <Text className="color">
                  {((data.totalFavourite / data.archiveView) * 100).toFixed(2)}
                </Text>
              </Text>
              <Text>
                播粉比:{' '}
                <Text className="color">
                  {((data.fans / data.archiveView) * 100).toFixed(2)}
                </Text>
              </Text>
              <Text>
                每百次播放评论:{' '}
                <Text className="color">
                  {((data.totalComment / data.archiveView) * 100).toFixed(2)}
                </Text>
              </Text>
              <Text>
                每百次播放弹幕:{' '}
                <Text className="color">
                  {((data.totalDanmaku / data.archiveView) * 100).toFixed(2)}
                </Text>
              </Text>
            </View>
          </AtCard>
          <AtDivider></AtDivider>
          <View style={{ marginLeft: '34rpx' }} className="cloud-wrap">
            <AtButton
              type="secondary"
              size="small"
              className={current_3 === 0 ? 'choose-btn' : 'scroll-btn'}
              onClick={() => setCurrent_3(0)}
            >
              标题关键字
            </AtButton>
            <AtButton
              type="secondary"
              size="small"
              className={current_3 === 1 ? 'choose-btn' : 'scroll-btn'}
              onClick={() => setCurrent_3(1)}
            >
              作品描述关键字
            </AtButton>
            <AtButton
              type="secondary"
              size="small"
              className={current_3 === 2 ? 'choose-btn' : 'scroll-btn'}
              onClick={() => setCurrent_3(2)}
            >
              作品标签关键字
            </AtButton>
          </View>
          <View className="page-index">
            <View className="line-chart">
              {/* 通过 option 设置数据 */}
              <EChart echarts={echarts} option={option_4} onInit={onInit} />
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

// return (
//   <View className="page-index">
//     <View className="line-chart">
//       {/* 通过 option 设置数据 */}
//       <EChart echarts={echarts} option={option} onInit={onInit} />
//     </View>
//   </View>
// )
